package _05_二叉树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
 */
public class _145_二叉树的后序遍历 {

    // 递归
    public List<Integer> postorderTraversal1(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        postorderTraversal(root, list);
        return list;
    }

    public void postorderTraversal(TreeNode node, List<Integer> list) {
        if (node == null) return;

        postorderTraversal(node.left, list);
        postorderTraversal(node.right, list);

        list.add(node.val);
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null)
            return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            // 左节点直接入栈
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            // 看是否存在右节点
            root = stack.peek();
            if (root.right == null || root.right == prev) {
                // 直接访问当前节点
                list.add(stack.pop().val);
                prev = root;
                root = null;
            } else {
                root = root.right;
            }
        }
        return list;
    }

    // 迭代，左，右，中
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if (root == null)
            return list;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        // 之前访问的节点
        TreeNode pre = null;
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.peek();
            if ((node.left == null && node.right == null) ||
                    (pre != null && (node.left == pre || node.right == pre))) {
                // 访问相对根节点
                node = stack.pop();
                list.add(node.val);
                pre = node;
            } else {
                if (node.right != null) stack.push(node.right);

                if (node.left != null) stack.push(node.left);

            }
        }
        return list;
    }

}
